#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
检查developer_statistics表是否存在
"""

import mysql.connector
from mysql.connector import Error
from utils.logger import sync_logger
from config.db_config import DB_CONFIG

def check_developer_table():
    """检查developer_statistics表是否存在"""
    sync_logger.log_info("开始检查developer_statistics表...")
    
    try:
        conn = mysql.connector.connect(**DB_CONFIG)
        cursor = conn.cursor()
        
        # 检查表是否存在
        cursor.execute("SHOW TABLES LIKE 'developer_statistics'")
        if cursor.fetchone():
            sync_logger.log_info("developer_statistics表存在")
            
            # 获取表结构
            cursor.execute("DESCRIBE developer_statistics")
            columns = cursor.fetchall()
            sync_logger.log_info("表结构如下:")
            for column in columns:
                sync_logger.log_info(f"字段: {column[0]}, 类型: {column[1]}")
                
            # 检查是否有数据
            cursor.execute("SELECT COUNT(*) FROM developer_statistics")
            count = cursor.fetchone()[0]
            sync_logger.log_info(f"表中现有 {count} 条数据")
            
            # 显示部分数据样例
            if count > 0:
                cursor.execute("SELECT * FROM developer_statistics LIMIT 5")
                rows = cursor.fetchall()
                sync_logger.log_info("数据样例:")
                for row in rows:
                    sync_logger.log_info(f"数据: {row}")
        else:
            sync_logger.log_info("developer_statistics表不存在，需要创建")
            
            # 创建表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS developer_statistics (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    username VARCHAR(255),
                    project_id INT NOT NULL,
                    commit_count INT DEFAULT 0,
                    mr_created_count INT DEFAULT 0,
                    mr_merged_count INT DEFAULT 0,
                    mr_reviewed_count INT DEFAULT 0,
                    issue_closed_count INT DEFAULT 0,
                    review_pass_rate FLOAT DEFAULT 0.0,
                    coverage FLOAT DEFAULT 0.0,
                    stats_date DATE NOT NULL,
                    UNIQUE KEY unique_user_project_date (user_id, project_id, stats_date)
                )
            ''')
            conn.commit()
            sync_logger.log_info("developer_statistics表创建成功")
            
    except Error as e:
        sync_logger.log_error(f"检查developer_statistics表时发生错误: {e}")
    finally:
        if conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == "__main__":
    check_developer_table() 